<template>
  <ElUpload
    size="small"
    :file-list="fileList"
    :action="uploadUrl"
    :headers="headers"
    list-type="picture-card"
    :on-success="onSuccess"
    :on-preview="onPictureCardPreview"
    :on-remove="onRemove"
  >
    <ElIcon><Plus /></ElIcon>
  </ElUpload>
  <ElDialog v-model="visible">
    <img w-full :src="imageUrl" alt="Preview Image" />
  </ElDialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElUpload, ElIcon, ElDialog } from 'element-plus'
import type { UploadFile } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const uploadUrl = import.meta.env.VITE_APP_API_BASE_URL + '/sys/file/upload'
const headers = { token: localStorage.getItem('token') }
function getFileName(url) {
  const l = url.split('/')
  return l[l.length - 1] || ''
}
interface Props {
  modelValue: string;
  data: object;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  data: () => ({})
})

interface Emits {
  'update:model-value': [string]
}
const emit = defineEmits<Readonly<Emits>>()

const fileList = computed(() => {
  if (!props.modelValue) return []
  return props.modelValue.split(',').map(i => ({
    name: getFileName(i),
    url: i
  }))
})

const onRemove = (_, fileList) => {
  emit('update:model-value', fileList.map(i => i.url).join(','))
}
const onSuccess = (response) => {
  const url = response.data?.url
  if (!url) return
  const val = [...fileList.value.map(i => i.url)]
  val.push(url)
  emit('update:model-value', val.join(','))
}

const visible = ref(false)
const imageUrl = ref('')
const onPictureCardPreview = (file: UploadFile) => {
  imageUrl.value = file.url!
  visible.value = true
}
</script>
